package com.snowy.hidden.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snowy.framework.common.base.dto.SlicedQueryResult;
import com.snowy.framework.common.base.vo.LoginUser;
import com.snowy.framework.common.resp.BaseResp;
import com.snowy.framework.common.resp.BaseRespUtil;
import com.snowy.hidden.biz.domain.model.QuestionBank;
import com.snowy.hidden.biz.domain.model.QuestionOptions;
import com.snowy.hidden.biz.domain.model.UserAnswers;
import com.snowy.hidden.biz.domain.model.UserScores;
import com.snowy.hidden.biz.domain.req.SubmitUserAnswersReq;
import com.snowy.hidden.biz.domain.resp.QuestionBankListResp;
import com.snowy.hidden.biz.domain.resp.SubmitUserAnswersResp;
import com.snowy.hidden.biz.mapper.QuestionBankMapper;
import com.snowy.hidden.biz.mapper.QuestionOptionsMapper;
import com.snowy.hidden.biz.mapper.UserAnswersMapper;
import com.snowy.hidden.biz.mapper.UserScoresMapper;
import com.snowy.hidden.biz.service.QuestionBankService;
import com.snowy.hidden.paging.PageQueryModel;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 问答题库表(QuestionBank)表服务实现类
 *
 * @author makejava
 * @since 2025-11-16 17:13:34
 */
@Service("questionBankService")
public class QuestionBankServiceImpl extends ServiceImpl<QuestionBankMapper, QuestionBank> implements QuestionBankService {

	@Resource
	private QuestionBankMapper questionBankMapper;
	@Resource
	private UserAnswersMapper userAnswersMapper;
	@Resource
	private QuestionOptionsMapper questionOptionsMapper;
	@Resource
	private UserScoresMapper userScoresMapper;

	@Override
	public BaseResp queryPage(PageQueryModel pageQueryModel) {
		Integer pageIndex = pageQueryModel.getPageIndex();
		Integer pageSize = pageQueryModel.getPageSize();
		//添加查询条件
		Wrapper queryWrapper = Wrappers.<QuestionBank>lambdaQuery();
		Page<QuestionBank> page = new Page<>(pageIndex,pageSize);
		//分页查询
		IPage<QuestionBank> iPage = questionBankMapper
				.selectPage(page,queryWrapper);
		SlicedQueryResult<QuestionBank> slicedQueryResult = new SlicedQueryResult<>(pageIndex,pageSize,iPage.getTotal(),iPage.getRecords());
		return BaseRespUtil.Success(slicedQueryResult);

	}

	@Override
	public List<QuestionBankListResp> queryList(LoginUser userRedisInfo) {
		List<QuestionBank> questionBankList= this.baseMapper.selectList(null);
		List<QuestionBankListResp> questionBankListRespList=new ArrayList<>();
		questionBankList.stream().forEach(questionBank -> {
			QuestionBankListResp questionBankListResp = new QuestionBankListResp();
			BeanUtils.copyProperties(questionBank,questionBankListResp);
			//通过用户id，查询用户问答记表表，如果有则标记为已答，如果没有则标记未未答
			LambdaQueryWrapper<UserAnswers> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(UserAnswers::getUserId,userRedisInfo.getUserId());
			queryWrapper.eq(UserAnswers::getQuestionId,questionBank.getQuestionId());
			if (userAnswersMapper.selectCount(queryWrapper).equals(0)){
				questionBankListResp.setReadFinish("未答");
			}else {
				questionBankListResp.setReadFinish("已答");
			}
			questionBankListRespList.add(questionBankListResp);
		});

		return questionBankListRespList;
	}

	@Override
	public List<QuestionOptions> getOptions(String questionId) {
		if (ObjectUtil.isNotEmpty(questionId)){
			LambdaQueryWrapper<QuestionOptions> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(QuestionOptions::getQuestionId,questionId);
			List<QuestionOptions>  templist=questionOptionsMapper.selectList(queryWrapper);
			//templist进行随机排序
			Collections.shuffle(templist);
			return templist;
		}
		return Collections.emptyList();
	}

	@Override
	@Transactional
	public SubmitUserAnswersResp submitquery(SubmitUserAnswersReq submitUserAnswersReq, LoginUser userRedisInfo) {
		//获取当前试题
		QuestionBank questionBank = questionBankMapper.selectById(submitUserAnswersReq.getQuestionId());
		//1、判断用户答题是否正确，通过问题获取正确的选项id
		LambdaQueryWrapper<QuestionOptions> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(QuestionOptions::getQuestionId,submitUserAnswersReq.getQuestionId());
		queryWrapper.eq(QuestionOptions::getIsCorrect,1);
		QuestionOptions questionOptions = questionOptionsMapper.selectOne(queryWrapper);
		if (questionOptions.getOptionId().equals(Long.valueOf(submitUserAnswersReq.getSelectedOptionId()))){
			//写入用户答题记录表
			UserAnswers userAnswers = new UserAnswers();
			userAnswers.setQuestionId(submitUserAnswersReq.getQuestionId());
			userAnswers.setUserId(userRedisInfo.getUserId());
			userAnswers.setSelectedOptionId(submitUserAnswersReq.getSelectedOptionId());
			userAnswers.setIsCorrect(1);
			userAnswersMapper.insert(userAnswers);

			//增加用户的积分表，积分表如果没有就增加，如果有就增加修
			LambdaQueryWrapper<UserScores> queryWrapperUserScores = new LambdaQueryWrapper<>();
			queryWrapperUserScores.eq(UserScores::getUserId,userRedisInfo.getUserId());
			UserScores userScores = userScoresMapper.selectOne(queryWrapperUserScores);
			Integer totalScore = 0;
			if (ObjectUtil.isNotEmpty(userScores)){
				totalScore=userScores.getTotalScore()+questionBank.getScore();
				userScores.setTotalScore(userScores.getTotalScore()+questionBank.getScore());
				userScoresMapper.updateById(userScores);
			}else {
				totalScore=questionBank.getScore();
				UserScores userScores1 = new UserScores();
				userScores1.setUserId(userRedisInfo.getUserId());
				userScores1.setTotalScore(questionBank.getScore());
				userScoresMapper.insert(userScores1);
			}
			//返回结果
			SubmitUserAnswersResp submitUserAnswersResp = new SubmitUserAnswersResp();
			submitUserAnswersResp.setExpectAnswer("正确");
			submitUserAnswersResp.setScore(questionBank.getScore());
			submitUserAnswersResp.setTotalScore(totalScore);
			return submitUserAnswersResp;
		}else {
			//增加用户的积分表，积分表如果没有就增加，如果有就增加修
			LambdaQueryWrapper<UserScores> queryWrapperUserScores = new LambdaQueryWrapper<>();
			queryWrapperUserScores.eq(UserScores::getUserId,userRedisInfo.getUserId());
			UserScores userScores = userScoresMapper.selectOne(queryWrapperUserScores);
			Integer totalScore = 0;

			//回答错误
			SubmitUserAnswersResp submitUserAnswersResp = new SubmitUserAnswersResp();
			submitUserAnswersResp.setExpectAnswer("错误");
			submitUserAnswersResp.setScore(0);

			if (ObjectUtil.isNotEmpty(userScores)){
				submitUserAnswersResp.setTotalScore(userScores.getTotalScore());
			}else {
				submitUserAnswersResp.setTotalScore(0);
			}
			return submitUserAnswersResp;

		}

	}
}
